package com.superms.platform.shiro;

import java.util.Collection;
import java.util.Set;

import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;

import com.jeesuite.cache.command.RedisBatchCommand;
import com.jeesuite.cache.command.RedisObject;
import com.jeesuite.cache.redis.JedisProviderFactory;
import com.jeesuite.mybatis.kit.CacheKeyUtils;

import redis.clients.util.SafeEncoder;

public class RedisCache<K, V> implements Cache<K, V> {

	private String keyPrefix;
	private String groupName = null;
	
	public RedisCache(String groupName,String cacheName) {
		this.groupName = groupName;
		keyPrefix = String.format("shiro.%s:", cacheName);
	}

	@Override
	public void clear() throws CacheException {
		RedisBatchCommand.removeByKeyPrefix(groupName, keyPrefix);
	}

	@Override
	public V get(K key) throws CacheException {
		String cacheKey = buildCacheKey(key);
		return new RedisObject(cacheKey).get();
	}

	@Override
	public Set<K> keys() {
		Set<byte[]> keys = JedisProviderFactory.getMultiKeyBinaryCommands(null).keys(SafeEncoder.encode(keyPrefix +"*"));
		if(keys != null && keys.size()>0){
			for(byte[] key:keys){}
		}
		throw new RuntimeException("Rediscache.keys 不支持");
	}

	@Override
	public V put(K key, V value) throws CacheException {
		String cacheKey = buildCacheKey(key);
		new RedisObject(cacheKey).set(value,3600);
		return value;
	}

	@Override
	public V remove(K key) throws CacheException {
		RedisObject cache = new RedisObject(buildCacheKey(key));
		V value = cache.get();
		if(value != null)cache.remove();
		return value;
	}

	@Override
	public int size() {
		try {			
			Set<byte[]> keys = JedisProviderFactory.getMultiKeyBinaryCommands(null).keys(SafeEncoder.encode(keyPrefix +"*"));
			return keys == null ? 0 : keys.size();
		} finally {
			JedisProviderFactory.getJedisProvider(groupName).release();
		}
	}

	@Override
	public Collection<V> values() {

		throw new RuntimeException("Rediscache.values 不支持");
	}
	
	private String buildCacheKey(K key){
		return keyPrefix + CacheKeyUtils.toString(key);
	}

}
